// import packages
import axios from 'axios';
import { BASE_URL, TIMEOUT } from '@/common/constants.js';
import { getUserToken } from '@/common/utils';

/* --------------------------------------------------------------
 *                       API Request Stance
 * -------------------------------------------------------------- */

/**
 * Axios instance for making HTTP requests.
 * @type {AxiosInstance}
 */
const apiClient = axios.create({
    baseURL: BASE_URL,
    timeout: TIMEOUT,
    headers: {
        'Content-Type': 'application/json',
    },
});

/**
 * Add request interceptor to check token
 */
apiClient.interceptors.request.use(
    (config) => {
        const token = getUserToken(); 

        // if token is not present and the request is not for login, redirect to login page
        if (config.url !== '/login/login' && !token) {
            console.error('Token missing. Please login.');
            return Promise.reject(new Error('Token missing. Please login.'));
        }

        // if token is present, add it to the request headers
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }

        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

/**
 * General API request function
 * @param {string} method - The HTTP method (GET, POST, PUT, DELETE)
 * @param {string} url - The API endpoint URL
 * @param {Object} [data] - The payload for POST and PUT requests
 * @param {Object} [params] - The query parameters for GET requests
 * @returns {Promise} - A Promise that resolves with the response data
 */
async function apiRequest(method, url, data = {}, params = {}) {
    try {
        const response = await apiClient({
            method,
            url,
            data,
            params,
        });
        return response.data;
    } catch (error) {
        console.error('接口请求失败：', error);
        throw error;
    }
};

export default apiRequest;